<template>
    <div class="user-list">
        <div class="header">
            <h2>User List</h2>
            <button class="add-user-btn" @click="toggleAddUserForm">
                Add User
            </button>
        </div>

        <!-- 显示用户添加表单的模态对话框 -->
        <div v-if="showAddUserForm" class="modal-overlay" @click="toggleAddUserForm">
            <div class="modal-content" @click.stop>
                <AddUserForm @userAdded="handleUserAdded" @cancel="toggleAddUserForm" />
            </div>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Roles</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in paginatedUsers" :key="user.id">
                        <td>{{ user.username }}</td>
                        <td>{{ user.email }}</td>
                        <td>{{ user.mobile }}</td>
                        <td>{{ user.role }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 分页控件 -->
        <div class="pagination">
            <span>Total {{ users.length }} users</span>
            <select v-model="pageSize" @change="changePageSize">
                <option value="5">5/page</option>
                <option value="10">10/page</option>
                <option value="20">20/page</option>
            </select>
            <button @click="changePage(currentPage - 1)" :disabled="currentPage <= 1">
                &lt;
            </button>
            <span>{{ currentPage }} / {{ totalPages }}</span>
            <button @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages">
                &gt;
            </button>

            <!-- 跳转到指定页功能 -->
            <div class="goto-page">
                <input type="number" v-model.number="goToPage" min="1" :max="totalPages" placeholder="Go to page" />
                <button @click="goToSpecifiedPage">Go</button>
            </div>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import AddUserForm from "./AddUserForm.vue";

export default {
    name: 'UserControl',
    components: {
        AddUserForm
    },
    data() {
        return {
            users: [],
            currentPage: 1,
            pageSize: 10,
            goToPage: "",
            showAddUserForm: false,
        };
    },
    computed: {
        paginatedUsers() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.users.slice(start, end);
        },
        totalPages() {
            return Math.ceil(this.users.length / this.pageSize);
        },
    },
    methods: {
        async fetchUsers() {
            try {
                const response = await axios.get("/api/users");
                this.users = response.data.map((user) => ({
                    ...user,
                    username: user.firstName + " " + user.lastName,
                }));

                const savedUser = JSON.parse(localStorage.getItem("userInfo"));
                if (savedUser) {
                    savedUser.username = savedUser.firstName + " " + savedUser.lastName;
                    this.users.push(savedUser);
                }

                if (this.currentPage > this.totalPages) {
                    this.currentPage = this.totalPages;
                }
            } catch (error) {
                console.error("获取用户数据失败:", error);
            }
        },
        changePage(page) {
            if (page > 0 && page <= this.totalPages) {
                this.currentPage = page;
            }
        },
        changePageSize() {
            if (this.currentPage > this.totalPages) {
                this.currentPage = this.totalPages;
            }
        },
        toggleAddUserForm() {
            this.showAddUserForm = !this.showAddUserForm;
        },
        handleUserAdded(newUser) {
            this.users.push(newUser);
            this.toggleAddUserForm();
        },
        goToSpecifiedPage() {
            const targetPage = parseInt(this.goToPage, 10);
            if (targetPage >= 1 && targetPage <= this.totalPages) {
                this.currentPage = targetPage;
            } else {
                alert(`请输入 1 到 ${this.totalPages} 之间的页码`);
            }
        }
    },
    created() {
        this.fetchUsers();
    },
    watch: {
        currentPage(newVal) {
            if (newVal < 1) {
                this.currentPage = 1;
            } else if (newVal > this.totalPages) {
                this.currentPage = this.totalPages;
            }
        },
        pageSize() {
            if (this.currentPage > this.totalPages) {
                this.currentPage = this.totalPages;
            }
        },
    },
};
</script>

<style scoped>
/* 用户列表的容器样式 */
.user-list {
    margin: 20px;
    margin-top: 0;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
}

/* 标题样式 */
h2 {
    text-align: left;
    margin-left: 50px;
}

/* 表格容器样式，用于溢出控制 */
.table-container {
    overflow-x: auto;
}

/* 表格样式 */
table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    padding: 15px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

th {
    background-color: #f5f5f5;
}

/* 分页控件样式 */
.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 跳转页码功能样式 */
.goto-page {
    display: flex;
    align-items: center;
}

.goto-page input {
    width: 100px;
    padding: 5px;
    margin-left: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

/* 按钮通用样式 */
button {
    padding: 5px 10px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:disabled {
    background-color: #ddd;
    cursor: not-allowed;
}

/* 添加用户按钮样式 */
.add-user-btn {
    background-color: #42b983;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

/* 模态框背景遮罩样式 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

/* 模态框内容样式 */
.modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    width: 600px;
    max-width: 90%;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    margin-bottom: 20px;
    background-color: #f5f5f5;
    border-radius: 8px;
}

/* 标题和按钮的间距调整 */
.header h2 {
    margin: 0;
}

.add-user-btn {
    padding: 10px 20px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
</style>